package com.aliyun.messagemgt.web.aop;

import com.alibaba.cola.dto.Response;
import com.aliyun.messagemgt.common.errorcode.IErrorCode;
import com.aliyun.messagemgt.common.exceptions.BaseException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Aspect
@Order(3)
public class PushResultPackageAop {

    private static final Logger logger = LoggerFactory.getLogger(PushResultPackageAop.class);

    /**
     * 切点为push所有controller包下方法
     */
    @Pointcut("execution(public * com.aliyun.messagemgt.web.controller.push..*(..))")
    public void controllerPoint() {
        //do nothing
    }

    @Around("controllerPoint()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("PushResultPackageAop before joinPoint.proceed");
        // 写了环绕增加后 不执行proceed该切点的其他方法将不能够执行
        Object object;
        // 捕获所有执行中发生的异常并打印封装
        try {
            object = joinPoint.proceed();
        }  catch (BaseException e) {
            logger.error("exception in {}", joinPoint.getSignature(), e);
            IErrorCode errorCode = e.getErrorCode();
            return Response.buildFailure(String.valueOf(errorCode.errCode()), errorCode.errName());
        } catch (Exception e) {
            logger.error("exception in {}", joinPoint.getSignature(), e);
            return Response.buildFailure(String.valueOf(1000), "unkonwn exception");
        }
        return object;
    }
}
